package com.code.demo.permission;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;

import static com.code.demo.config.HandlerEvent.PERMISSION_FAIL;
import static com.code.demo.config.HandlerEvent.PERMISSION_SUCCESS;


/**
 * Created by yangliguo on 2018/3/22.
 */

public class PermissionManager {

    private Context context;
    private Handler handler;

    public PermissionManager(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
    }

    public void requestPermission(String... permissions) {
        AndPermission.with(context)
                .permission(permissions)
                .rationale(new DefaultRationale())
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        handler.sendEmptyMessage(PERMISSION_SUCCESS);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        handler.sendEmptyMessage(PERMISSION_FAIL);
                        if (AndPermission.hasAlwaysDeniedPermission(context, permissions)) {
                            new PermissionSetting(context).showSetting(permissions);
                        }
                    }
                })
                .start();
    }

    public void requestPermission(String[]... permissions) {
        AndPermission.with(context)
                .permission(permissions)
                .rationale(new DefaultRationale())
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        handler.sendEmptyMessage(PERMISSION_SUCCESS);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        handler.sendEmptyMessage(PERMISSION_FAIL);
                        if (AndPermission.hasAlwaysDeniedPermission(context, permissions)) {
                            new PermissionSetting(context).showSetting(permissions);
                        }
                    }
                })
                .start();
    }
}
